import request from '../../../utils/request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showModalStatus: false, //是否显示
    selectSpuId: 0, //选中的规格ID
    ggText: '', //规格文本
    ggPrice: 0, //规格价格
    // guigeList: [{ guige: '100', price: '150' }, { guige: '200', price: '150' }, { guige: '300', price: '150' }],
    num: 1, //初始数量
    goodsInfo: {},
    goodsId: 0,
    spuInfo: [],
    selectSpu: {},
    ggImage: '',
    checked:false
  },

  takeOrder() {
    this.setData({
      showModalStatus: true
    })
  },

  toIndex() {
    wx.switchTab({
      url: "/pages/index/index"
    })
  },

  toCart() {
    wx.switchTab({
      url: "/pages/cart/cart"
    })
  },

  /**
   * 隐藏栏点击规格
   */
  filter: function(e) {
    var self = this;
    let spec = e.currentTarget.dataset.spec
    let value = e.currentTarget.dataset.value
    let spuInfo = this.data.spuInfo
    let selectSpu = this.data.selectSpu
    for (let i = 0; i < spuInfo.length; i++) {
      if (spuInfo[i].spu == spec) {
        let valueArray = spuInfo[i].value;
        for (let j = 0; j < valueArray.length; j++) {
          valueArray[j].checked = false;
          if (valueArray[j].value == value) {
            valueArray[j].checked = true;
            // selectSpu.replace(spuInfo[i].spu + ":" + valueArray[j].value)
          }
        }
        break;
      }
    }
    // console.log(spec)
    let selectSpuArray = selectSpu.split(",");
    let selectSpuNewArray = [];
    let ggTextArray = [];
    for (let spuIndex in selectSpuArray) {
      if (selectSpuArray[spuIndex].indexOf(spec) != -1) {
        selectSpuNewArray.push(spec + ":" + value)
        ggTextArray.push(value)
        continue;
      }
      selectSpuNewArray.push(selectSpuArray[spuIndex])
      ggTextArray.push(selectSpuArray[spuIndex].substr(selectSpuArray[spuIndex].indexOf(":") + 1))
    }
    selectSpu = selectSpuNewArray.join(",");

    let selectSpuId = this.data.selectSpuId;
    let productData = this.data.goodsInfo.goodsProductDto;
    let ggPrice = this.data.ggPrice;
    let ggImage = this.data.ggImage;
    // console.log(selectSpu)
    // console.log(selectSpuId)
    for (let productIndex in productData) {
      if (productData[productIndex].specifications == selectSpu) {
        ggPrice = productData[productIndex].price;
        ggImage = productData[productIndex].picUrl;
        selectSpuId = productData[productIndex].id;
        break;
      }
    }


    let ggText = ggTextArray.join(" ")
    self.setData({
      selectSpuId,
      ggText,
      ggPrice,
      spuInfo,
      selectSpu,
      ggImage
    });
  },

  /* 点击减号 */
  bindMinus: function() {
    var num = this.data.num;
    // 如果大于1时，才可以减  
    if (num > 1) {
      num--;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态  
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    // 将数值与状态写回  
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
  /* 点击加号 */
  bindPlus: function() {
    var num = this.data.num;
    // 不作过多考虑自增1  
    num++;
    // 只有大于一件的时候，才能normal状态，否则disable状态  
    var minusStatus = num < 1 ? 'disabled' : 'normal';
    // 将数值与状态写回  
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },

  //显示对话框
  showModal: function() {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function() {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },

  /**
   * 添加到购物车
   */
  async addCart() {
    let data = this.data;
    let productId = data.selectSpuId;
    let goodsId = data.goodsId;
    let num = data.num;
    let result = await request('/cart/post', {
      productId,
      goodsId,
      num
    }, 'POST');
    if (result.code == 200) {
      wx.showToast({
        title: '加入购物车成功！该商品在购物车处等着您~',
        icon: 'none'
      })
      this.setData({
        showModalStatus: false
      })
    } else if(result.status == 401) {
      wx.navigateTo({
        url: `/pages/auth/auth`
      })
      return;
    } else {
      wx.showToast({
        title: '系统繁忙，请稍后再试！',
        icon: 'none'
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function(options) {
    let goodsId = options.goodsId;
    let result = await request('/goods/detail', {
      goodsId
    });
    if (result.code == -1) {
      this.data.checked = true;
      wx.showToast({
        title: '该商品已下架！3秒内自动返回上一页！',
        icon: 'none'
      })

      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        })
      }, 3000);
     
      return;
    }
    let spuInfo = this.data.spuInfo;
    let selectSpuArray = [];
    let ggTextArray = [];
    let selectSpuId = this.data.selectSpuId;
    // 定义规格组装
    let spec = result.data.goodsSpecDto
    for (let index in spec) {
      let spuInfoRes = {
        spu: '',
        value: []
      };
      spuInfoRes.spu = spec[index].specifications;
      let valueRes = spec[index].value.split(",");
      for (let indexValue in valueRes) {
        let valueEntity = {
          value: '',
          checked: false
        };
        valueEntity.value = valueRes[indexValue];
        if (indexValue == 0) {
          // 默认选中规格
          valueEntity.checked = true;
          selectSpuArray.push(spuInfoRes.spu + ":" + valueRes[indexValue]);
          ggTextArray.push(valueRes[indexValue]);
        }
        spuInfoRes.value.push(valueEntity)
      }
      this.data.spuInfo.push(spuInfoRes)
    }
    // 选中规格
    let selectSpu = selectSpuArray.join(",");
    let ggText = ggTextArray.join(" ");
    let productData = result.data.goodsProductDto;
    let ggPrice = this.data.ggPrice;
    let ggImage = this.data.ggImage;
    for (let productIndex in productData) {
      if (productData[productIndex].specifications == selectSpu) {
        ggPrice = productData[productIndex].price;
        ggImage = this.data.picUrl;
        selectSpuId = productData[productIndex].id;
        break;
      }
    }
    // 选中的规格id价格
    this.setData({
      goodsId,
      goodsInfo: result.data,
      spuInfo,
      selectSpu,
      selectSpuId,
      ggText,
      ggPrice,
      ggImage
    })
    // console.log(this.data.ggText)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})